﻿/// <reference path="~/Scripts/Library/jquery-1.9.1.min.js" />

function Sponsor_ParentSponsorId_OnSelect(event, e) {

    $("#Sponsor_ThroughProgramId").empty();

    if (e.item) {

        // VALID SELECTION, SEE IF THERE ARE ANY PROGRAMS AVAILABLE 

        $("#Sponsor_ThroughProgramId").removeAttr("disabled");

        ParentSponsor_ProgramSelection_Initialize();

    }

    else {

        // NOT A VALID SELECTION, CLEAR DEPENDENT DROP DOWN 

        $("#Sponsor_ThroughProgramId").attr("disabled", "disabled");

    }

}

function Sponsor_EnrollThroughSelection_OnClick() {

    var isDirect = $("input[name=Sponsor_EnrollThroughSelection]:checked").val();


    if (isDirect == "1") {

        $("#Sponsor_DirectProgramId").removeAttr("disabled");

        $("#Sponsor_ParentSponsorId").attr("disabled", "disabled");

        $("#Sponsor_ThroughProgramId").attr("disabled", "disabled");

    }

    else {

        $("#Sponsor_DirectProgramId").attr("disabled", "disabled");

        $("#Sponsor_ParentSponsorId").removeAttr("disabled");

        $("#Sponsor_ThroughProgramId").removeAttr("disabled");

    }

}

function Sponsor_ParentSponsorId_AutoCompleteSource(request, responseCallback) {
    
    var requestUrl = $("#RootUrl").val() + "Sponsor/SponsorEnrollAvailableParentAutoComplete";

    requestUrl += "?EffectiveDate=" + $("#Sponsor_Enrollment_EffectiveDate").val();

    requestUrl += "&ChildSponsorTypeId=" + $("#Sponsor_SponsorTypeId").val();

    requestUrl += "&term=" + request.term;


    $.ajax({

        url: requestUrl,

        method: "GET",

        error: function (jqXHR, textStatus, errorThrown) {

            responseCallback([{ label: "Error: " + errorThrown, value: "" }]);

        },

        success: function (data, textStatus, jqXHR) {

            responseCallback(data);

        },

        complete: function () {

            $("ul.ui-autocomplete a").removeClass("ui-corner-all");

        }

    });

}

function ParentSponsor_ProgramSelection_Initialize(request, responseCallback) {

    $("#Sponsor_ThroughProgramId_ProgressBar").show();

    $("#Sponsor_ThroughProgramId").empty();


    var requestUrl = $("#RootUrl").val() + "Sponsor/SponsorEnrollProgramsByParentSponsor";

    requestUrl += "?EffectiveDate=" + $("#Sponsor_Enrollment_EffectiveDate").val();

    requestUrl += "&ParentSponsorId=" + $("#Sponsor_SponsorTypeId").val();
    

    $.ajax({

        url: requestUrl,

        method: "GET",

        error: function (jqXHR, textStatus, errorThrown) {

            $("#Sponsor_ThroughProgramId").append($("<option>Error: " + errorThrown + "</option>"));

        },

        success: function (response, textStatus, jqXHR) {

            if (response.HasException) {

                $("#Sponsor_ThroughProgramId").append($("<option>Error: " + response.ExceptionMessage + "</option>"));

            }

            else {

                $(response.Objects).each(function () {

                    $("#Sponsor_ThroughProgramId").append($("<option value=\"" + this.Id + "\">" + this.Name + "</option>"));


                });

            }

        },

        complete: function () {

            $("#Sponsor_ThroughProgramId_ProgressBar").hide();

        }



    });

}


function LastResponseMessage_ClearError() {

    var lastResponseMessageLabel = $("#LastResponseMessageLabel");

    lastResponseMessageLabel.html("");

    lastResponseMessageLabel.parent().removeClass("ui-state-error");

    return;

}

function LastResponseMessage_SetError(errorMessage) {

    var lastResponseMessageLabel = $("#LastResponseMessageLabel");

    lastResponseMessageLabel.html(errorMessage);

    lastResponseMessageLabel.parent().addClass("ui-state-error");

    return;

}

function Validate() {

    var isValid = true;


    // RESET ALL FIELD CHANGES 

    $(".ui-state-error").removeClass("ui-state-error");

    LastResponseMessage_ClearError();


    // TODO: VALIDATE 
    
    var isDirect = $("input[name=Sponsor_EnrollThroughSelection]:checked").val();


    if ((isDirect == "1") && ($("#Sponsor_DirectProgramId").val() == "")) {

        $("td:nth-child(2)", $("#Sponsor_DirectProgramId").closest("tr")).addClass("ui-state-error");

        isValid = false;

    }
        
    if (isDirect == "0") {

        if ($("#Sponsor_ParentSponsorId").val() == "") {

            $("td:nth-child(2)", $("#Sponsor_ParentSponsorId").closest("tr")).addClass("ui-state-error");

            isValid = false;

        }

        if (($("#Sponsor_ThroughProgramId").val() == "") || ($("#Sponsor_ThroughProgramId").val() == null)) {

            $("td:nth-child(2)", $("#Sponsor_ThroughProgramId").closest("tr")).addClass("ui-state-error");

            isValid = false;

        }

    }
    
    return isValid;

}



function OkApply_OnClick(sender) {

    var isValid = Validate();

    if (!isValid) { return; }


    LastResponseMessage_ClearError();

    var lastResponseMessageLabel = $("#LastResponseMessageLabel");

    lastResponseMessageLabel.html("Saving...");

    $("#AjaxWorking").show();


    $("#ButtonContainer button").attr("disabled", "disabled");


    var postbackUrl = $("#RootUrl").val() + "Sponsor/SponsorEnroll";

    $.ajax({

        type: "POST",

        url: postbackUrl,

        data: $("form").serialize(),

        error: function (jqXHR, textStatus, errorThrown) {

            alert("Error performing AJAX page request: " + errorThrown + " [Url:" + postbackUrl + "]");

            LastResponseMessage_SetError(errorThrown);

        },

        success: function (response) {

            if (response.Result) {

                LastResponseMessage_ClearError();

                $("#LastResponseMessageLabel").text("Save successful.");

                // CALL REFRESH ON PARENT (HOME) PAGE 

                if (window.opener) {

                    // TODO

                }

                window.close();

            }

            else {

                LastResponseMessage_SetError(response.ExceptionMessage);

            }

        },

        complete: function () {

          $("button").removeAttr("disabled");

          $("#AjaxWorking").hide();

        }

    });

}

function Cancel_OnClick(sender) {

    window.close();

}


$(document).ready(function () {

    // INITIALIZE PAGE 
    
    $("body").addClass("ui-state-default-background");

    $("#ApplicationContent").removeClass("ui-state-default-background ui-state-default-border");

    $("#ApplicationTitleBarLinkHome").closest("td").hide();

    $("#ApplicationTitleBarLinkClose").closest("td").hide();

    $("#ApplicationTitleBarLinkLogout").closest("td").hide();

    $("#ApplicationTitleLabel").text("| Sponsor Enroll");


    // ALL BUTTONS 

    $("button").button();


    // DATE PICKERS 

    $(".InputDate").datepicker({

        showOtherMonths: true,

        selectOtherMonths: true,

        showOn: "button",

        buttonImage: $("#RootUrl").val() + "Assets/Images/Common16/Calendar.png",

        buttonImageOnly: false

    });

    $("button.ui-datepicker-trigger").button();

    $("button.ui-datepicker-trigger").css("border", "0px");

    $("button.ui-datepicker-trigger").css("margin-left", "4px");

    $("button.ui-datepicker-trigger span").css("padding", "0px");

    $("button.ui-datepicker-trigger span").css("margin", "0px");

    $("button.ui-datepicker-trigger span").css("border", "0px");

    $("button.ui-datepicker-trigger span").css("height", "16px");


    // SET INITIAL EFFECTIVE DATE 

    $('#Sponsor_Enrollment_EffectiveDate').datepicker("setDate", new Date());


    // ENROLL THROUGH SELECTION 

    $("input[name=Sponsor_EnrollThroughSelection]:first").attr("checked", "checked");

    Sponsor_EnrollThroughSelection_OnClick();


    // PARENT SPONSOR AUTO COMPLETE 

    $("#Sponsor_ParentSponsorId").autocomplete({

        minLength: 3,

        select: Sponsor_ParentSponsorId_OnSelect,

        source: Sponsor_ParentSponsorId_AutoCompleteSource

    });


    $("ul.ui-autocomplete").css("font-size", "8pt");

    $("ul.ui-autocomplete").removeClass("ui-corner-all");



    


    // SET UP AJAX PROGRESS BAR 

    ProgressBar_AjaxUnder_Initialize("Sponsor_ThroughProgramId_ProgressBar");


    $("#Sponsor_Enrollment_EffectiveDate").focus();

});